import { useMemo } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { BellOutline } from 'antd-mobile-icons'
import './TopHeader.css'

interface TopHeaderProps {
  // 是否隐藏中间的搜索占位框（例如在病友圈首页隐藏）
  hideSearch?: boolean
}

const TopHeader = ({ hideSearch = false }: TopHeaderProps) => {
  const navigate = useNavigate()
  const location = useLocation()

  // 是否已登录（用于头像点击逻辑）
  const isLoggedIn = useMemo(() => !!localStorage.getItem('token'), [location.key])

  // 是否为首页：仅在首页展示搜索框（头像和右侧图标始终展示）
  const isHomePage = location.pathname === '/'
  const showSearch = isHomePage && !hideSearch

  const handleAvatarClick = () => {
    if (!isLoggedIn) {
      navigate('/login')
    }
  }

  return (
    <div className="top-header" role="banner">
      {/* 左侧头像：未登录点击跳转登录 */}
      <button className={`avatar ${isLoggedIn ? 'logged-in' : 'guest'}`} onClick={handleAvatarClick} aria-label={isLoggedIn ? '用户头像' : '去登录'}>
        {isLoggedIn ? '🙂' : '👤'}
      </button>

      {/* 中间搜索框：仅首页显示，占位无交互 */}
      {showSearch && (
        <div className="search-box" role="search">
          <input className="search-input" type="text" placeholder="请输入症状/疾病" readOnly />
        </div>
      )}

      {/* 右侧消息图标：始终显示，样式用 margin-left:auto 右对齐 */}
      <button className="message-btn" aria-label="消息">
        <BellOutline />
      </button>
    </div>
  )
}

export default TopHeader


